package  net.libra.ui.controls
{
	import flash.events.Event;
	import flash.text.TextField;
	
	import net.libra.ui.base.BaseGrid;
	import net.libra.ui.event.BaseEvent;

	public class SearchGridControl
	{
		protected var baseGrid:BaseGrid;
		protected var textField:TextField;
		protected var propertys:Array;
		protected var callback:Function;
		protected var defaultText:String;
		protected var source:Array;
		public function SearchGridControl(baseGrid:BaseGrid,textField:TextField,defaultText:String,propertys:Array,callback:Function=null)
		{
			this.baseGrid = baseGrid;
			this.textField = textField;
			this.defaultText = defaultText||"";
			this.propertys = propertys||[];
			this.callback = callback;
			if(this.callback == null)
			{
				this.callback = innerCallBack;
			}
			
			this.source = this.baseGrid.source;
			this.textField.addEventListener(Event.CHANGE,searchChange);
			this.baseGrid.addEventListener(BaseEvent.DATA_CHANGE,dataChange);
		}
		
		public function destroy():void
		{
			textField.removeEventListener(Event.CHANGE,searchChange);
			baseGrid.removeEventListener(BaseEvent.DATA_CHANGE,dataChange);
			baseGrid.source = source;
			source = [];
			callback = null;
		}
		
		
		protected function innerCallBack(content:String,item:Object,list:Array):Boolean
		{
			if(!content)
			{
				return true;
			}
			content = content.toLowerCase();
			for(var i:uint=0;i<propertys.length;i++)
			{
				var prop:String = propertys[i];
				prop = String(item[prop]);
				prop = prop.toLowerCase();
				if(prop && prop.indexOf(content)!=-1)
				{
					return true;
				}
			}
			return false;
		}
		
		
		protected function dataChange(event:Event):void
		{
			source = baseGrid.source;
			update();
		}
		protected function searchChange(event:Event):void
		{
			update();
		}
		protected function update():void
		{
			baseGrid.removeEventListener(BaseEvent.DATA_CHANGE,dataChange);
			baseGrid.source = filter();
			baseGrid.addEventListener(BaseEvent.DATA_CHANGE,dataChange);
		}
		protected function filter():Array
		{
			var content:String = textField.text;
			if(content == defaultText)
			{
				content = "";
			}
			if(!content)
			{
				return source;
			}
			
			var i:uint=0;
			var list:Array = [];
			
			for(i=0;i<source.length;i++)
			{
				var item:Object = source[i]
				if(callback(content,item,source))
				{
					list.push(item);
				}
			}
			return list;
		}
	}
}